package com.caishi.lkx.user.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.user.model.AgentNoticeModel;
import com.caishi.lkx.user.service.IAgentNoticeService;
import com.caishi.lkx.user.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author huangpeng
 * @Date 2022/9/26 15:04
 **/
@RestController
@RequestMapping("/user/cu/agent/notice")
public class AgentNoticeApi extends AdminBaseApi<IAgentNoticeService, AgentNoticeModel, String> {
    @Resource
    private IAgentNoticeService service;

    @Resource
    private IUserService userService;

    @Override
    public IAgentNoticeService loadService() {
        return service;
    }

    @Override
    protected LambdaQueryWrapper<AgentNoticeModel> baseWrapper(AgentNoticeModel model, JSONObject otherParam) {
        String noticeKey = otherParam.getStr("noticeKey");
        return super.baseWrapper(model.clearEmptyStringField("title"), otherParam)
                .like(StrUtil.isNotBlank(noticeKey), AgentNoticeModel::getTitle, noticeKey);
    }

    @Override
    protected List<AgentNoticeModel> listCover(List<AgentNoticeModel> result, JSONObject otherParam) {
        return result.parallelStream().peek(r -> {
            r.setCreatedBy(userService.getUserNameById(r.getCreatedBy()));
        }).toList();

    }

    @PostMapping("/update")
    @Override
    public AgentNoticeModel add(@RequestBody AgentNoticeModel entity) {
        entity.setPublishTime(LocalDateTime.now());
        return loadService().insert(entity);
    }

    @PutMapping("/publish")
    public AgentNoticeModel publish(@RequestBody AgentNoticeModel entity) {
        if (entity.getStatus()) entity.setPublishTime(LocalDateTime.now());
        return loadService().simpleUpdate(entity);
    }
}
